package com.common.util;

import com.common.entity.User;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

/**
 * @author hcq
 */
public class JWTUtil {

    public static Integer EXPIRE_TIME = 60*24;

    /**
     * 私有化
     */
    private JWTUtil() {

    }

    /**
     * 生成公钥和私钥
     *
     * @param publicFilename
     * @param privateFilename
     * @param secret
     */
    public static void generateKey(String publicFilename, String privateFilename, String secret) {
        try {
            RsaUtils.generateKey(publicFilename, privateFilename, secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成令牌的方法
     *
     * @param user
     * @param privateKey
     * @return
     */
    public static String generateToken(User user, String privateKey) {
        String token = "";
        try {
            token = Jwts.builder().claim("userId", user.getId())
                    .claim("roleSign",user.getRoleSign())
                    .claim("avatar",user.getAvatar())
                    .claim("account",user.getAccount())
                    .setExpiration(DateTime.now().plusMinutes(EXPIRE_TIME).toDate())
                    .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey)).compact();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 解析令牌
     *
     * @param token
     * @param publicKey
     * @return
     */
    public static User parserToken(String token, String publicKey) throws Exception {

        Claims body = Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey)).parseClaimsJws(token).getBody();
        String userId = body.get("userId", String.class);
        String roleSign = body.get("roleSign",String.class);
        String avatar = body.get("avatar",String.class);
        String account = body.get("account",String.class);

        User user = new User();
        user.setId(userId);
        user.setAccount(account);
        user.setRoleSign(roleSign);
        user.setAvatar(avatar);

        return user;
    }

}
